package other.system.client.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.data.model.Account;
import com.rkhd.platform.sdk.exception.XsyHttpException;
import com.rkhd.platform.sdk.http.CommonData;
import com.rkhd.platform.sdk.http.CommonHttpClient;
import com.rkhd.platform.sdk.http.HttpResult;
import com.rkhd.platform.sdk.http.RkhdBlob;
import com.rkhd.platform.sdk.http.RkhdFile;
import com.rkhd.platform.sdk.http.RkhdHttpClient;
import com.rkhd.platform.sdk.http.RkhdHttpData;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 功能描述：文件上传/下载处理类
 *
 * @author 王宏泽
 * @ClassName: FileServive
 * @Description:
 * @date 2022年5月18日
 */
public class FileServive {

    /**
     * 下载图片或文件字节流
     *
     * @param downUrl
     * @return
     * @throws XsyHttpException
     */
    public static RkhdBlob downBlob(String downUrl) throws XsyHttpException {
        // 使用CommonHttpClient下载外部系统的文件
        CommonData data = CommonData.newBuilder().callString(downUrl).callType("GET").build();
        RkhdBlob rkhdBlob = CommonHttpClient.instance().downBlob(data);
        if (rkhdBlob.getFileName() == null || rkhdBlob.getFileName().length() == 0) {
            // fileName 不能为空;应该包括文件名和扩展名
            String fileSuffix = getFileSuffix(downUrl);
            if (fileSuffix == null) {
                // 获取不到文件类型
                return null;
            }
            String fileName = UUID.randomUUID().toString().replace("-", "");
            fileName = fileName + "." + fileSuffix;
            rkhdBlob.setFileName(fileName);
        }
        return rkhdBlob;
    }

    /**
     *
     *
     * @param downUrl
     * @return
     * @throws XsyHttpException
     */
    public static RkhdFile downFile(String downUrl) throws XsyHttpException {
        // 使用CommonHttpClient下载外部系统的文件
        CommonData data = CommonData.newBuilder().callString(downUrl).callType("GET").build();
        RkhdFile rkhdFile = CommonHttpClient.instance().downFile(data);
        if (rkhdFile.getFileName() == null || rkhdFile.getFileName().length() == 0) {
            // fileName 不能为空;应该包括文件名和扩展名
            String fileSuffix = getFileSuffix(downUrl);
            if (fileSuffix == null) {
                // 获取不到文件类型
                return null;
            }
            String fileName = UUID.randomUUID().toString().replace("-", "");
            fileName = fileName + "." + fileSuffix;
            rkhdFile.setFileName(fileName);
        }
        return rkhdFile;
    }


    /**
     * 上传文件到销售易 此接口在paas只支持单个文件上传
     *
     * @param token
     * @param rkhdBlob 字节文件
     * @return
     */
    public static JSONObject uploadFile(String token, RkhdBlob rkhdBlob) {
        CommonData data = CommonData.newBuilder()
                .callType("POST")
                .callString("https://api-p05.xiaoshouyi.com/rest/file/v2.0/file/batch")
                .header("Authorization", "Bearer " + token)
                .formType("formData")
                .mimeType("multipart/form-data")
                .formData("files", rkhdBlob)
                .formData("needFileId", true)
                .build();
        HttpResult result = CommonHttpClient.instance().execute(data);
        JSONObject jsonObject = JSONObject.parseObject(result.getResult());
        return jsonObject;
    }

    /**
     * 上传图片到销售易
     *
     * @param token
     * @param rkhdBlob
     * @return
     */
    public static JSONObject uploadImage(String token, RkhdBlob rkhdBlob) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("files", rkhdBlob);
        CommonData data = CommonData.newBuilder().callString("https://api-p05.xiaoshouyi.com/rest/file/v2.0/image")
                .callType("POST")
                .header("Authorization", token)
                .formType(CommonData.formDataType.formData)
                .formData(map)
                .build();
        HttpResult result = CommonHttpClient.instance().execute(data);
        JSONObject jsonObject = JSONObject.parseObject(result.getResult());
        return jsonObject;
    }

    /**
     * 上传图片至s3服务
     *
     * @param imageUrlList 图片url集合
     * @return
     * @throws IOException
     * @throws XsyHttpException
     */
    public static JSONObject uploadImageS3(List<String> imageUrlList) throws IOException, XsyHttpException {
        RkhdHttpData crmData = new RkhdHttpData();
        crmData.setCall_type("POST");
        crmData.setCallString("/rest/auto/v2.0/file/image/upload");
        crmData.setBody(JSONObject.toJSONString(imageUrlList));
        String res = RkhdHttpClient.instance().execute(crmData, e -> e);
        JSONObject resutl = JSONObject.parseObject(res);
        return resutl;
    }

    /**
     * 通过仁科互动的方式上传文件
     * @param blob
     * @return
     * @throws IOException
     * @throws XsyHttpException
     */
    public static JSONObject upload(RkhdBlob blob) throws IOException, XsyHttpException {
        RkhdHttpData up = RkhdHttpData.newBuilder().callString("/rest/file/v2.0/file/batch").callType("POST").build();
        up.putFormData("files",blob);
        up.putFormData("needFileId",true);
        up.putFormData("isImage",false);
        up.putHeader("Content-Type", "form-data");
        String execute = RkhdHttpClient.instance().execute(up, e -> e);
        JSONObject jsonObject = JSONObject.parseObject(execute);
        return jsonObject;
    }

    /**
     * 通过url方式获取文件流
     * @param urlPath
     * @return
     */
    public static byte[] getFileByteByUrl(String urlPath) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            InputStream inputStream = new URL(urlPath).openStream();
            byte[] buffer = new byte[1024 * 4];
            int n = 0;
            while (-1 != (n = inputStream.read(buffer))) {
                output.write(buffer, 0, n);
            }
            return output.toByteArray();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取文件名后缀
     *
     * @param str
     * @return
     */
    private static String getFileSuffix(String str) {
        String[] splitArr = str.split("\\.");
        int length = splitArr.length;
        if (length <= 0) {
            return null;
        }
        return splitArr[length - 1];
    }

//    public static void main(String[] args) throws XsyHttpException, IOException {
//        String fileUrl = "https://xsybucket.s3.cn-north-1.amazonaws.com.cn/1948913424732463/2022/05/18/c69b2cc1-72bb-409e-890d-ad16eff89f8a.csv";
//        RkhdBlob rkhdBlob = downBlob(fileUrl);
////        JSONObject upload = upload(rkhdBlob);
////        System.out.println(upload);
//    }


    public static void main(String[] args) throws Exception {

        String urlFile = "https://crmtencentprod-1253467224.cos.ap-guangzhou.myqcloud.com/1562592989170327/2022/06/10/dbb717ef-861d-4b88-96a3-523eae53c4c1.pdf";

        byte[] fileByteByUrl = getFileByteByUrl(urlFile);

        RkhdBlob rkhdBlob = new RkhdBlob();
        rkhdBlob.setBytes(fileByteByUrl);

        if (rkhdBlob == null) {
            // 下载文件失败，获取不到文件类型
            return;
        }

        String token = "4285bfc4d5a59b9db2e7214c5ccd9f929bba10e0f45cf70286cc4926db39adb1.OTk3NDU3NDY2ODAyNTc20";

        rkhdBlob.setFileName("测试文件.pdf");

        JSONObject jsonObject = uploadFile(token, rkhdBlob);

        System.out.println(jsonObject);

        Integer code = jsonObject.getInteger("code");
        if (code == null || code != 200) {
            // 上传文件失败
            return;
        }
        JSONArray result = jsonObject.getJSONArray("result");
        JSONObject fileInfo = result.getJSONObject(0);
        String fileId = fileInfo.getString("fileId");

        Account account = new Account();
        List<Map> listMap = new ArrayList<>();
        Map<String, Long> fileMap = new HashMap<>();
        fileMap.put("id", Long.valueOf(fileId));
        listMap.add(fileMap);


        account.setId(2295058394268330L);
        HCXObjectService hcxObjectService = new HCXObjectService();
        System.out.println("更新结果：" + hcxObjectService.update(account));
    }




}
